package CompletableFuturefd;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.*;

@Configuration
@EnableAsync
@Slf4j

public class ThreadPoolConfig {

    static final int blockingQueueCapacity = 5000;

    static final int keepAliveTime = 60;

    static final int availableProcessors = Runtime.getRuntime().availableProcessors();

    static final int corePoolSize  = availableProcessors * 2;

    static final int maximumPoolSize = 50;

    static {
        log.info("[availableProcessors]={},corePoolSize={},maximumPoolSize={}",availableProcessors,corePoolSize,maximumPoolSize);
    }

    /**
     * 通用线程池配置
     * @return
     */
    @Bean
    public ExecutorService threadPoolExecutor() {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("common-pool-%d").build();
        return new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(blockingQueueCapacity), threadFactory);
    }

    /**
     * 跑批大数据量线程池配置
     * blockingQueueCapacity 需要设置合理大小；即便线程池已满，使用拒绝策略；有补偿机制。
     * @return
     */
    @Bean
    public ExecutorService disposeOrderHandleThreadPool() {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("disposeOrder-pool-%d").build();
        final int corePoolSize = availableProcessors * 6,maxPoolSize = corePoolSize * 2,keepAliveTime = 60,blockingQueueCapacity = 5000;
        return new ThreadPoolExecutor(corePoolSize,maxPoolSize,keepAliveTime, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(blockingQueueCapacity), threadFactory);
    }

}

